/**
 * @file packet_base.h
 * @author HaoyuWang (136046355@qq.com)
 * @brief packet处理基类，使用：先调用Begin(cmd)，再调用WriteXXX()，最后调用End()
 * @version 0.1
 * @date 2025-02-13
 * 
 * @copyright Copyright (c) 2025
 * 
 */
#ifndef __PACKET_BASE_H__
#define __PACKET_BASE_H__

#include <cstdint>
#include <vector>
#include <string>

#include "common.h"

class __attribute__((visibility("default"))) PacketBase
{
private:
    uint16_t buffer_size_;
    uint32_t buffer_pos_;
    // char buffer_[common::PROTO_BUFFER_LEN];
    char* buffer_;

private:
    void WriteHeader(char* c, uint32_t len, uint32_t pos);
    void ReadHeader(char* c, uint32_t len, uint32_t pos);
    void Read(char* c, uint32_t len, uint32_t pos);
    void Read(char* c, uint32_t len);

public:
    PacketBase();
    ~PacketBase();

    void Reset();
    void ResetPos();

    void Copy(const void *buf, uint32_t len);
    void CopyHeader(uint32_t len, uint32_t cmd);
    void CopyBody(const char* body, uint32_t len);
    inline char* GetBuffer(){
        char* tmp = buffer_;
        buffer_ = nullptr;
        buffer_size_ = 0;
        return tmp;
    }

    inline char* GetOriginBuffer(){
        return buffer_;
    }

    inline uint16_t GetBufferSize(){
        return buffer_size_;
    }

    void Begin(uint16_t cmd);
    void End();
    void Write(const char* c, uint32_t len);
    
    uint16_t GetCmd();
    uint16_t GetBodySize();

    void WriteInt16(int16_t val);
    void WriteString(const std::string& str);
    void WriteZero();

    int16_t ReadInt16();
    std::string ReadString();
};


#endif  // __PACKET_BASE_H__